import express, { Request, Response, NextFunction, Application } from 'express';
import cors from 'cors';
import path from 'path';
import dotenv from 'dotenv';

dotenv.config();

const app: Application = express();
const PORT: number = parseInt(process.env.PORT || '3000', 10);

// 中间件配置
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// API路由
const apiPrefix = '/api/v1';

// 导入路由
import authRouter from './routes/auth';
import navbarRouter from './routes/navbar';
import homepageRouter from './routes/homepage';
import contactRouter from './routes/contact';
import settingsRouter from './routes/settings';

// 注册路由
app.use(`${apiPrefix}/auth`, authRouter);
app.use(`${apiPrefix}/navbar`, navbarRouter);
app.use(`${apiPrefix}/homepage`, homepageRouter);
app.use(`${apiPrefix}/contact`, contactRouter);
app.use(`${apiPrefix}/settings`, settingsRouter);

// 健康检查接口
app.get('/health', (req: Request, res: Response): void => {
  res.json({
    status: 'ok',
    timestamp: new Date().toISOString(),
    uptime: process.uptime()
  });
});

// 404处理
app.use('*', (req: Request, res: Response): void => {
  res.status(404).json({
    success: false,
    message: '接口不存在'
  });
});

// 全局错误处理中间件
app.use((err: Error, req: Request, res: Response, next: NextFunction): void => {
  console.error('服务器错误:', err);
  
  // 开发环境返回详细错误信息
  if (process.env.NODE_ENV === 'development') {
    res.status(500).json({
      success: false,
      message: err.message,
      stack: err.stack
    });
  } else {
    // 生产环境返回通用错误信息
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

// 启动服务器
function startServer(): void {
  try {
    app.listen(PORT, (): void => {
      console.log(`🚀 服务器启动成功`);
      console.log(`📍 服务地址: http://localhost:${PORT}`);
      console.log(`🌍 环境: ${process.env.NODE_ENV || 'development'}`);
      console.log(`📊 健康检查: http://localhost:${PORT}/health`);
    });
  } catch (error) {
    console.error('❌ 服务器启动失败:', error);
    process.exit(1);
  }
}

// 优雅关闭
process.on('SIGTERM', (): void => {
  console.log('收到SIGTERM信号，正在关闭服务器...');
  process.exit(0);
});

process.on('SIGINT', (): void => {
  console.log('收到SIGINT信号，正在关闭服务器...');
  process.exit(0);
});

startServer();

export default app;